package com.jianqiao.delivery.mail;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import org.apache.commons.codec.binary.Base64;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * author: cyx
 * create: 2024/11/22 9:50
 **/
public class GmailTest {
    public static void main(String[] args) throws MessagingException, IOException {
        FileInputStream serviceAccountStream = new FileInputStream("D://项目/物流网/前台/RuoYi-Vue-master/ruoyi-admin/src/main/resources/credentials_web.json");
        System.out.println(System.getenv().keySet());
        //凭据方法1
        GoogleCredentials credentials = GoogleCredentials
                .fromStream(serviceAccountStream)
//                .getApplicationDefault()
                .createScoped(GmailScopes.GMAIL_SEND);
        //凭据方法2
        GoogleCredential credential = new GoogleCredential().setAccessToken("accessToken");

//        HttpCredentialsAdapter requestInitializer = new HttpCredentialsAdapter(credential);
        HttpRequestInitializer requestInitializer = credential;

        //创建谷歌消息
        Gmail service = new Gmail.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("Gmail samples")
                .build();
        String messageSubject = "Test message";
        String bodyText = "lorem ipsum.";
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage email = new MimeMessage(session);
        email.setFrom(new InternetAddress("thesofo303@gmail.com"));
        email.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress("xuyuan0602@gmail.com"));
        email.setSubject(messageSubject);
        email.setText(bodyText);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        email.writeTo(buffer);
        byte[] rawMessageBytes = buffer.toByteArray();
        String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes);
        Message message = new Message();
        message.setRaw(encodedEmail);

        try {
            // Create send message
            message = service.users().messages().send("me", message).execute();
            System.out.println("Message id: " + message.getId());
            System.out.println(message.toPrettyString());
//            return message;
        } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            GoogleJsonError error = e.getDetails();
            if (error.getCode() == 403) {
                System.err.println("Unable to send message: " + e.getDetails());
            } else {
                throw e;
            }
        }
    }
}
